package com.cd.miniprogramServer.controller;

import com.cd.miniprogramServer.common.result.Result;
import com.cd.miniprogramServer.common.web.Results;
import com.cd.miniprogramServer.dto.req.CreateUserReqDTO;
import com.cd.miniprogramServer.dto.req.UpdateUserReqDTO;
import com.cd.miniprogramServer.dto.resp.UserRespDTO;
import com.cd.miniprogramServer.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Tag(name = "用户管理", description = "用户相关的接口")
public class UserController {
    
    private final UserService userService;
    
    @GetMapping("/getOne")
    @Operation(summary = "获取单个用户", description = "获取一个用户的信息")
    public UserRespDTO getOneUser() {
        return userService.getOneUserDTO();
    }
    
    @GetMapping("/getOneUser")
    @Operation(summary = "获取单个用户(包装)", description = "获取一个用户的信息，使用Result包装")
    public Result<UserRespDTO> getOneUser_1() {
        return Results.success(userService.getOneUserDTO());
    }
    
    @PostMapping("/create")
    @Operation(summary = "创建用户", description = "创建一个新的用户")
    public Result<Boolean> createUser(@RequestBody CreateUserReqDTO reqDTO) {
        return Results.success(userService.createUser(reqDTO));
    }
    
    @PostMapping("/update")
    @Operation(summary = "更新用户", description = "更新用户信息")
    public Result<Boolean> updateUser(@RequestBody UpdateUserReqDTO reqDTO) {
        return Results.success(userService.updateUser(reqDTO));
    }
    
    @GetMapping("/getUserById")
    @Operation(summary = "根据ID获取用户", description = "根据用户ID获取用户信息")
    public Result<UserRespDTO> getUserById(@Parameter(description = "用户ID") @RequestParam String id) {
        try {
            Long userId = Long.parseLong(id);
            UserRespDTO userRespDTO = userService.getUserById(userId);
            if (userRespDTO == null || userRespDTO.getId() == null) {
                // 如果用户不存在，返回一个空对象而不是null
                return Results.success(new UserRespDTO());
            }
            return Results.success(userRespDTO);
        } catch (NumberFormatException e) {
            // 如果ID不是有效的数字，返回空对象
            return Results.success(new UserRespDTO());
        }
    }
    
    @DeleteMapping("/deleteUserById")
    @Operation(summary = "根据ID删除用户", description = "根据用户ID删除用户")
    public Result<Boolean> deleteUserById(@Parameter(description = "用户ID") @RequestParam String id) {
        try {
            Long userId = Long.parseLong(id);
            return Results.success(userService.deleteUserById(userId));
        } catch (NumberFormatException e) {
            // 如果ID不是有效的数字，返回false
            return Results.success(false);
        }
    }
}